//
//  ATDetailViewController.m
//  Adorable_Things
//
//  Created by huzhiyan on 16/1/13.
//  Copyright © 2016年 Banana Inc. All rights reserved.
//

#import "ATDetailViewController.h"
#import "ATMainDetailViewController.h"
#import "ATIntroModel.h"
#import "ATDetailFirstSectionTableViewCell.h"
#import "ATDetailSecondSectionTableViewCell.h"
#import "ATDetailThirdSectionTableViewNoneCell.h"
#import "ATDetailFirstSectionHeaderView.h"
#import "ATDetailSecondSectionHeaderView.h"
#import "ATDetailThirdSectionHeaderView.h"
#import "DJShopViewController.h"
#import "SDCycleScrollView.h"
#import "ATShareFootView.h"
#import "UMSocial.h"

@interface ATDetailViewController () <UITableViewDataSource,UITableViewDelegate,SDCycleScrollViewDelegate>

@property (nonatomic, strong) NSMutableArray *pic_urlArray;
@property (nonatomic, strong) ATIntroModel *introModel;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) SDCycleScrollView *headerView;


@end

@implementation ATDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self addSubTableView];
    [self setUpData];
}

#pragma mark --- 请求数据
- (void)setUpData
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"item_id"] = _item_id;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:@"http://api.menghuoapp.com/v1/item/related_shop" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dataDic = responseObject[@"data"];
        if (![dataDic isKindOfClass:[NSNull class]]) {
            _introModel = [[ATIntroModel alloc] init];
            [_introModel setValuesForKeysWithDictionary:dataDic];
            _pic_urlArray = [NSMutableArray array];
            NSArray *items = dataDic[@"items"];
            for (NSDictionary *modelDic in items) {
                ATIntroModel *pic_urlModel = [[ATIntroModel alloc] init];
                pic_urlModel.pic_url = modelDic[@"pic_url"];
                pic_urlModel.item_id = modelDic[@"item_id"];
                pic_urlModel.name = modelDic[@"name"];
                [_pic_urlArray addObject:pic_urlModel];
            }
            [_tableView reloadData];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];

}

#pragma mark --- 添加TableView视图
- (void)addSubTableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 65) style:(UITableViewStyleGrouped)];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView registerClass:[ATDetailFirstSectionTableViewCell class] forCellReuseIdentifier:@"ATDetailFirstSectionTableViewCell"];
    [_tableView registerClass:[ATDetailSecondSectionTableViewCell class] forCellReuseIdentifier:@"ATDetailSecondSectionTableViewCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"ATDetailThirdSectionTableViewNoneCell" bundle:nil] forCellReuseIdentifier:@"ATDetailThirdSectionTableViewNoneCell"];
    
    ATShareFootView *footView = [[ATShareFootView alloc]initWithFrame:CGRectMake(0, 30, kWidth , 100)];
    
    _tableView.tableFooterView = footView;
    
   [footView.weixinBut addTarget:self action:@selector(weixinAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [footView.friendBut addTarget:self action:@selector(friendButAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [footView.weibo addTarget:self action:@selector(weiboAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [footView.QQBut addTarget:self action:@selector(QQButAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [footView.QQzoneBut addTarget:self action:@selector(QQzoneButAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
}

#pragma mark --- 分享方法实现
// 分享方法
- (void)weixinAction:(UIButton *)button
{
     NSString *str = [NSString stringWithFormat:@"我在Adorable_Things关注了%@",_introModel.name];
    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatSession] content:str image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            NSLog(@"分享成功！");
        }
    }];

}

- (void)friendButAction:(UIButton *)button
{
    NSString *str = [NSString stringWithFormat:@"我在Adorable_Things关注了%@",_introModel.name];
    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatTimeline] content:str image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            NSLog(@"分享成功！");
        }
    }];
}

- (void)weiboAction:(UIButton *)button
{
    NSString *str = [NSString stringWithFormat:@"我在Adorable_Things关注了%@",_introModel.name];
    [[UMSocialControllerService defaultControllerService] setShareText:str shareImage:[UIImage imageNamed:@"icon_120"] socialUIDelegate:nil];        //设置分享内容和回调对象
    [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina].snsClickHandler(self,[UMSocialControllerService defaultControllerService],YES);
   
}

- (void)QQButAction:(UIButton *)button
{
     NSString *str = [NSString stringWithFormat:@"我在Adorable_Things关注了%@",_introModel.name];
    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToQQ] content:str image:[UIImage imageNamed:@"L108"] location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            NSLog(@"分享成功！");
        }
    }];
}

- (void)QQzoneButAction:(UIButton *)button
{
    NSString *str = [NSString stringWithFormat:@"我在Adorable_Things关注了%@",_introModel.name];
    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToQzone] content:str image:[UIImage imageNamed:@"L108"] location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            NSLog(@"分享成功！");
        }
    }];
}

#pragma mark --- 添加轮播图View
// 添加轮播图View
- (void)addSubHeaderScrollView
{
    _headerView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kWidth, kWidth / 1.2) imageURLStringsGroup:_model.pic_urls];
    _headerView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    _headerView.delegate = self;
    _headerView.currentPageDotColor = [UIColor redColor];
    _headerView.pageDotColor = [UIColor grayColor];
    self.tableView.tableHeaderView = _headerView;
}

#pragma mark --- UITableViewDataSource,UITableViewDelegate 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_pic_urlArray != nil) {
        return 3;
    } else {
        return 2;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_model != nil) {
        [self addSubHeaderScrollView];
    }
    if (indexPath.section == 0) {
        ATDetailFirstSectionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ATDetailFirstSectionTableViewCell" forIndexPath:indexPath];
        cell.model = _model;
        [cell.priceButton addTarget:self action:@selector(priceButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    // 判断第二个分区是不是为空
    if (_pic_urlArray != nil) {
        // 不为空创建第二个分区cell
        if (indexPath.section == 1) {
            ATDetailSecondSectionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ATDetailSecondSectionTableViewCell" forIndexPath:indexPath];
            cell.pic_urlArray = _pic_urlArray;
            [cell.collectionView reloadData];
            __weak ATDetailViewController *myself = self;
            cell.block = ^ void (NSNumber *itemID) {
                ATMainDetailViewController *atMainVC = [[ATMainDetailViewController alloc] init];
                atMainVC.item_id = itemID;
                [myself.navigationController pushViewController:atMainVC animated:YES];
            };
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
            // 不为空创建第三个分区cell
        } else if (indexPath.section == 2) {
            ATDetailThirdSectionTableViewNoneCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ATDetailThirdSectionTableViewNoneCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
        // 为空就直接把第三个分区当成第二个分区
    } else {
        ATDetailThirdSectionTableViewNoneCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ATDetailThirdSectionTableViewNoneCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    return nil;
}
// 分区表头
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        ATDetailFirstSectionHeaderView *headerView = [[[UINib nibWithNibName:@"ATDetailFirstSectionHeaderView" bundle:nil] instantiateWithOwner:self options:nil] lastObject];
        headerView.titleLabel.text = _model.title;
        return headerView;
    }
    if (_pic_urlArray != nil) {
        if (section == 1) {
            ATDetailSecondSectionHeaderView *headerView = [[[UINib nibWithNibName:@"ATDetailSecondSectionHeaderView" bundle:nil] instantiateWithOwner:self options:nil] lastObject];
            [headerView.iconImageView sd_setImageWithURL:[NSURL URLWithString:_introModel.logo]];
            headerView.nameLabel.text = _introModel.name;
            headerView.introLabel.text = _introModel.intro;
            headerView.tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
            [headerView addGestureRecognizer:headerView.tapGesture];
            return headerView;
        } else if (section == 2) {
            ATDetailThirdSectionHeaderView *headerView = [[ATDetailThirdSectionHeaderView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 60)];
            return headerView;
        }
    } else {
        ATDetailThirdSectionHeaderView *headerView = [[ATDetailThirdSectionHeaderView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 60)];
        return headerView;
    }
    return nil;
}



// 每个cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (_model.buyer_comment.length != 0) {
            CGFloat height = [ATDetailFirstSectionTableViewCell cellHeightForModel:_model] + 20;
            return 70 + height;
        }
        return 70;
    }
    if (_pic_urlArray != nil) {
        if (indexPath.section == 1) {
            return kWidth / 4 + 40;
        } else if (indexPath.section == 2) {
            return kWidth / 4 + 40;
        }
    } else {
        return kWidth / 4 + 40;
    }
    return 135;
}

// 每个分区的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 90;
    }
    if (_pic_urlArray != nil) {
        if (section == 1) {
            return 100;
        } else if (section == 2) {
            return 60;
        }
    } else {
        return 60;
    }
    return 100;
}

#pragma mark --- 实现分区一价格button的点击方法
- (void)priceButtonClick:(UIButton *)button
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_model.click_url]];
}

#pragma mark --- 实现分区二表头的手势点击方法
// 实现分区二表头的手势点击方法
- (void)tapAction:(UITapGestureRecognizer *)tapGesture
{
    DJShopViewController *djShopVC = [[DJShopViewController alloc] init];
    djShopVC.shop_id = [NSString stringWithFormat:@"%@",_introModel.shop_id];
    [self.navigationController pushViewController:djShopVC animated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
